<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="司机所属机构:" class="merge-item" :table-form-merge="1.5">
        <el-tree-select
          v-model="query.driverOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
        <div style="width: 120px; padding-left: 20px;">
          <el-checkbox v-model="query.option" label="包含下级" />
        </div>
      </el-form-item>
      <el-form-item :table-form-merge="1.2">
        <el-input v-model.trim="query.param" style="width: 300px;" placeholder="请输入" clearable>
          <el-select slot="prepend" v-model="qtype" style="width: 140px;" placeholder="请选择">
            <el-option label="绑定司机编号" value="driverCode" />
            <el-option label="绑定司机姓名" value="driverName" />
            <el-option label="客户姓名" value="csmName" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户电话" value="csmPhone" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label="用户类型:">
        <el-select v-model="query.csmType" placeholder="请选择" clearable>
          <el-option v-for="(item,index) in customerTypeMap" :key="index" :label="item.desc" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="押金类型:">
        <el-select v-model="query.depositType" placeholder="请选择" clearable>
          <el-option v-for="item in depositTypeMap" :key="item.value" :label="item.desc" :value="item.value" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[10020306,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <addQuotedPriceUser ref="addQuotedPriceUser" :customer-type-map="customerTypeMap" :parent-fetch-data="upDataTable" />
  </div>
</template>

<script>
  import {
    queryMap,
    queryDriverCsmPriceList
  } from '@/api'
  import { parseTime } from '@/utils'
  import { formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import addQuotedPriceUser from './addQuotedPriceUser'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  export default {
    name: '',
    components: {
      CsmDetail,
      addQuotedPriceUser
    },
    props: {
      priceStatusMap: {
        type: Array,
        default() {
          return []
        }
      }
    },
    data() {
      return {
        treeData: [],
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方式枚举
        customerTypeMap: [],
        depositTypeMap: [
          { desc: '50型押金用户', value: 1 },
          { desc: '非50型押金用户', value: 2 },
          { desc: '无押金用户', value: 3 },
          { desc: '混合型押金用户', value: 4 }
        ],
        feeTypeMap: [
          { desc: '市场价', value: 1 },
          { desc: '市场价打折', value: 2 },
          { desc: '固定价', value: 3 },
          { desc: '按距离设置', value: 4 }
        ],
        floorTypeMap: [
          { desc: '市场价', value: 1 },
          { desc: '市场价打折', value: 2 },
          { desc: '固定价', value: 3 }
        ],
        qtype: null,
        query: {
          driverOrgSNNo: null,
          csmType: null,
          depositType: null,
          param: '',
          option: false
        },
        tableData: {
          total: 0,
          data: []
        },
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          { label: '绑定司机编号',
            prop: 'driverCode',
            width: 110
          },
          {
            label: '绑定司机',
            prop: 'driverName'

          },
          {
            label: '司机所属机构',
            prop: 'driverOrgName',
            showOverflowTooltip: true
          },
          {
            label: '用户编号',
            prop: 'csmCode',
            width: 105,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          )
          },
          {
            label: '用户姓名',
            prop: 'csmName',
            width: 110,
            showOverflowTooltip: true
          },
          {
            label: '用户电话',
            prop: 'csmPhone',
            width: 110
          },
          {
            label: '联系地址',
            prop: 'csmAddress',
            showOverflowTooltip: true
          },
          {
            label: '用户所属机构',
            prop: 'orgName',
            showOverflowTooltip: true
          },
          {
            label: '用户类型',
            prop: 'csmType',
            width: 80,
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', Number(row.csmType), 'desc') }</span>
          },
          {
            label: '用户押金类型',
            prop: 'depositType',
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.depositType && formatColumnMap(this.depositTypeMap, 'value', row.depositType, 'desc') }</span>
          },
          {
            label: '报价状态',
            prop: '',
            showOverflowTooltip: true,
            render: (h, { row }) => { return row.priceStatus ? <span>{ row.priceStatus && formatColumnMap(this.priceStatusMap, 'value', row.priceStatus, 'desc') }</span> : '' }
          },
          {
            label: '操作',
            className: 'action-col',
            width: 80,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      {(<el-dropdown-item>
                        <el-link v-permission={[10020306, 2]} underline={false} size='mini' onClick={() => this.setPrice(row)}>
                          设置报价
                        </el-link>
                      </el-dropdown-item>)}
                      {row.priceStatus && (
                      <el-dropdown-item>
                        <el-link v-permission={[10020306, 3]} underline={false} size='mini' onClick={() => this.detail(row)}>
                          查看报价
                        </el-link>
                      </el-dropdown-item>)}
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      this.getTreeData()
      await Promise.all([this.queryOptionsMap()])
      this.$nextTick(() => {
        this.$refs.lbTable.fetch()
      })
    },
    beforeDestroy() {
    },
    methods: {
      // 查询字典枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        ])
        this.calcTypeList = res1.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res2.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.customerTypeMap = res3.data // 客户类型
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.driverOrgId = value.orgId
        this.query.driverOrgName = value.orgName
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        query.driverOrgId = this.query.option ? 0 : this.query.driverOrgId
        return query
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage, pageSize }) {
        this.pageSize = pageSize
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.param !== '') {
          query[this.qtype] = this.query.param
        }
        const res = await queryDriverCsmPriceList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      search() {
        if (!this.qtype && this.query.param) {
          this.$message.warning('请选择查询条件')
          return
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 查看客户详情
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 新增报价
      async setPrice(row) {
        this.$refs.addQuotedPriceUser.open(row, '新增')
      },
      // 查看报价
      async detail(row) {
        this.$refs.addQuotedPriceUser.open(row, '查看')
      },
      // 更新表格
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') < parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')) {
          return 'danger-row'
        }
        return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    display: flex;
    width: 50%;
    padding-right: 10px;
    // .el-form-item__content {
    //   width: 100%;
    // }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffdfdf;
}
.down-btn {
  position: absolute;
  top: 62px;
  left: 590px;
}
.tip {
  margin-top: 20px;
  color: #F56C6C;
}
.red {
  color: #F56C6C;
}
</style>
